<?php

namespace app\admin\controller\pifa;

use app\common\controller\Backend;
use think\Db;
use app\admin\model\pifa\ActivitySku;
use app\admin\model\litestore\Litestoregoodsspec as SpecModel;
use app\admin\model\litestore\Litestoregoods;


/**
 * 营销活动
 *
 * @icon fa fa-circle-o
 */
class Activity extends Backend
{

    /**
     * Activity模型对象
     * @var \app\admin\model\pifa\Activity
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pifa\Activity;


        $shangjia = Db::table('fa_pifa_shangjia')->select();
        $this->assignconfig('shangjia',$shangjia);

    }

     /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $type = $this->request->param('type', null);

        if (!$this->request->isAjax()) {
          return $this->view->fetch();

        }

        $activities = $this->model->paginate(request()->param('list_rows', 10))->toArray();

        $items = $activities['data'];

        // 关联活动的商品
        $goodsIds = array_values(array_filter(array_column($items, 'goods_ids')));
        $goodsIdsArr = [];
        foreach ($goodsIds as $ids) {
            $idsArr = explode(',', $ids);
            $goodsIdsArr = array_merge($goodsIdsArr, $idsArr);
        }
        $goodsIdsArr = array_values(array_filter(array_unique($goodsIdsArr)));
        if ($goodsIdsArr) {
            // 查询商品
            $goods = Litestoregoods::where('goods_id', 'in', $goodsIdsArr)->select();
            $goods = array_column($goods, null, 'goods_id');
        }
        $shangjia = Db::table('fa_pifa_shangjia')->column('*',"id");

        // var_dump($shangjia);
        foreach ($items as $key => $activity) {
             $items[$key]['shangjia'] = [];
            $items[$key]['goods'] = [];
            if ($activity['goods_ids']) {
                $idsArr = explode(',', $activity['goods_ids']);
                foreach ($idsArr as $id) {
                    if (isset($goods[$id])) {
                        $items[$key]['goods'][] = $goods[$id];
                    }
                }
            }
            $items[$key]['start_time'] = date('Y-m-d H:i:s',$activity['start_time']);
            $items[$key]['end_time'] = date('Y-m-d H:i:s',$activity['end_time']);
            $items[$key]['createtime'] = date('Y-m-d H:i:s',$activity['createtime']);
            $items[$key]['updatetime'] = date('Y-m-d H:i:s',$activity['updatetime']);
            if (!empty($activity['shangjia_id']) && isset($shangjia[$activity['shangjia_id']])) {
              $items[$key]['shangjia'] = $shangjia[$activity['shangjia_id']];
            }
        }




        $activities['data'] = $items;

        $this->success('获取成功', null, $activities);
    }



     /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function add()
    {   


        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }


        $post = $this->request->request();


        $insdata['title'] = $post['title'];
        $insdata['goods_ids'] = $post['goods_ids'];
        $insdata['shangjia_id'] = $post['shangjia_id'];
        $insdata['start_time'] = strtotime($post['start_time']);
        $insdata['end_time'] = strtotime($post['end_time']);
        $insdata['createtime'] = time();
        $insdata['updatetime'] = time();

        $id = Db::table('fa_pifa_activity')->insertGetId($insdata);

      

        $goods_list = json_decode($post['goods_list'],true);

        $goods_ids = [];
        foreach ($goods_list as $key => $value) {
           
           if (isset($value['activity_sku_prices']) && !empty($value['activity_sku_prices'])) {
              $insdata2 = [];
              $insdata2['stock'] = $value['activity_sku_prices'][0]['stock'];
              $insdata2['sales'] = $value['activity_sku_prices'][0]['sales'];
              $insdata2['price'] = $value['activity_sku_prices'][0]['price'];
              $insdata2['createtime'] = time();
              $insdata2['updatetime'] = time();
              $insdata2['status'] = $value['activity_sku_prices'][0]['status'];
              $insdata2['activity_id'] = $id;
              $insdata2['goods_sku_price_id'] = $value['goods_id'];
              $insdata2['goods_id'] = $value['goods_id'];
              Db::table('fa_pifa_activity_sku_price')->insertGetId($insdata2);
              array_push($goods_ids, $value['goods_id']); 
           }
           
        }

        if (!empty($goods_ids)) {
            $updata['goods_ids'] = implode(',', $goods_ids);
        }else{
            $updata['goods_ids'] = '';
        }


        $map['id'] = $id;
        $id = Db::table('fa_pifa_activity')->where($map)->update($updata);

        
       $this->success('获取成功', null, []);
    }  


     /**
     * 详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $activity = $this->model->where('id', $id)->find();
        if (!$activity) {
            $this->error(__('No Results were found'));
        }
        $activity->goods_list = $activity->goods_list;
        $activity->rules = [];
        $activity = $activity->toArray();
        $activity['start_time'] = date('Y-m-d H:i:s',$activity['start_time']);
        $activity['end_time'] = date('Y-m-d H:i:s',$activity['end_time']);

        

        $this->success('获取成功', null, $activity);
    }



     /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function edit($ids = null)
    {   

        if (!$this->request->isAjax()) {
            return $this->view->fetch('add');
        }

       
        $post = $this->request->request();


        

      

        $goods_list = json_decode($post['goods_list'],true);
       
        $ids = [];
        $goods_ids = [];
        $map2['activity_id'] = $post['id'];
        Db::table('fa_pifa_activity_sku_price')->where($map2)->delete();
        foreach ($goods_list as $key => $value) {
           if (isset($value['activity_sku_prices']) && !empty($value['activity_sku_prices'])) {
                  $insdata2 = [];
                  $insdata2['stock'] = $value['activity_sku_prices'][0]['stock'];
                  $insdata2['sales'] = $value['activity_sku_prices'][0]['sales'];
                  $insdata2['price'] = $value['activity_sku_prices'][0]['price'];
                  $insdata2['createtime'] = time();
                  $insdata2['updatetime'] = time();
                  $insdata2['status'] = $value['activity_sku_prices'][0]['status'];
                  $insdata2['activity_id'] = $post['id'];
                  $insdata2['goods_sku_price_id'] = $value['activity_sku_prices'][0]['goods_sku_price_id'];
                  $insdata2['goods_id'] = $value['goods_id'];
                  $idnow = Db::table('fa_pifa_activity_sku_price')->insertGetId($insdata2);
                  array_push($goods_ids, $value['goods_id']);  
           } 
        }



        if (!empty($goods_ids)) {
            $insdata['goods_ids'] = implode(',', $goods_ids);
        }else{
            $insdata['goods_ids'] = '';
        }

        $insdata['title'] = $post['title'];
        $insdata['shangjia_id'] = $post['shangjia_id'];
        $insdata['start_time'] = strtotime($post['start_time']);
        $insdata['end_time'] = strtotime($post['end_time']);
        $insdata['createtime'] = time();
        $insdata['updatetime'] = time();
        $map['id'] = $post['id'];
        $id = Db::table('fa_pifa_activity')->where($map)->update($insdata);


        $this->success('更新成功');
    }

     /**
     * 获取活动商品规格并且初始化
     */
    public function skus()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $params = $this->request->param();
        $id = $params['id'] ?? 0;
        $goods_id = $params['goods_id'] ?? 0;
        $activity_type = $params['activity_type'] ?? '';
        $start_time = $params['start_time'] ?? '';
        $end_time = $params['end_time'] ?? '';
        $prehead_time = $params['prehead_time'] ?? '';

        if ($start_time && $end_time && $activity_type) {
            // 如果存在开始结束时间，并且是要修改
            $goodsList = [$goods_id => ['id' => $goods_id]];

            $this->checkActivityConflict([
                'type' => $activity_type,
                'classify' => $this->model->getClassify($activity_type),
                'start_time' => $start_time,
                'end_time' => $end_time,
                'prehead_time' => $prehead_time
            ], $goodsList, $id);
        }


        $skus = [];

        $skuPrices = SpecModel::with(['activity_sku_price' => function ($query) use ($id) {
            $query->where('activity_id', $id);
        },'goods'])->where('fa_litestore_goods_spec.goods_id', $goods_id)->select();


        //编辑
        $activitySkuPrices = [];
        foreach ($skuPrices as $k => $skuPrice) {
            $activitySkuPrices[$k] = $skuPrice->activity_sku_price ? $skuPrice->activity_sku_price->toArray() : [];
            // 活动规格数据初始化
            if (!$activitySkuPrices[$k]) {
                $activitySkuPrices[$k]['id'] = 0;
                $activitySkuPrices[$k]['status'] = 'down';
                $activitySkuPrices[$k]['price'] = '';
                $activitySkuPrices[$k]['stock'] = '';
                $activitySkuPrices[$k]['sales'] = '0';
                $activitySkuPrices[$k]['goods_sku_price_id'] = $skuPrice->goods_spec_id;
            }

           
        }

        $this->success('获取成功', null, [
            'skus' => $skus,
            'sku_prices' => $skuPrices,
            'activity_sku_prices' => $activitySkuPrices,
        ]);
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function delete($id = null){

      
        $map['id'] = $id;
        Db::table('fa_pifa_activity')->where($map)->delete();


        $map2['activity_id'] = $id;
        Db::table('fa_pifa_activity_sku_price')->where($map2)->delete();
        $this->success('删除成功');
    }

}
